﻿var fileUploadUrl = "/_layouts/Sukul.SharePoint.Taxomatic/TaxomaticHandler.ashx?mode=import";

///
/// Calls a web service using JSONP
///
function CallWebService(url, input, callBack) {
    var request = null;
    if (input != null) {
        request = { "Args": input};
        request = "request=" + JSON.stringify(request);
    }
    $.getJSON(url, request, callBack);
}

function Version_Entry_Load() {
    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetVersion", null, onSuccessGetVersion);    
}

function Entry_Load() {
    ShowProgress();

    $("#myTestMenu").splitbutton({ plain: true, menu: '#myMenu' });
    $("#btnVersion").button();
    $("#btnImport").button();
    $("#btnExport").button();
    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetTerms", null, onSuccessGetTerms);
    Bannerize();
    //CallWebService(null, "GetTerms");

}

function Import_Load() {
    $("#txtImport").button();
    /* Upload control */
    var button = $('#txtImport'), interval;
    var upload = new AjaxUpload(button, {
        action: fileUploadUrl,
        name: 'TaxonomyImport',
        onSubmit: function (file, ext) {
            //checking file extension
            if (!(ext && /^(xml)$/.test(ext))) {
                // extension is not allowed
                alert('Error: invalid file extension');
                // cancel upload
                return false;
            }

            // change button text, when user selects file			
            button.text('Importing');

            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();

            // Importing -> Importing. -> Importing..
            interval = window.setInterval(function () {
                var text = button.text();
                if (text.length < 12) {
                    button.text(text + '.');
                } else {
                    button.text('Importing');
                }
            }, 400);
        },
        onComplete: function (file, response) {
            button.text('Upload');
            window.clearInterval(interval);

            // enable upload button
            this.enable();
            // add file to the picturebox
            var extension = (file.substr(file.indexOf(".") + 1, file.length - file.indexOf(".") - 1));
            window.frameElement.commitPopup();
            window.frameElement.commonModalDialogClose(1, 1);
        }
    });

}

/* Converts the supplied div tag into a banner */
function Bannerize() {
    //$(".prev").button();
   // $(".next").button();
    $("#banner").jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        auto: 2000,
        speed: 5000,
        visible: 1
    });
};

function ShowProgress() {
    $("#Progress").show();
}

function HideProgress() {
    $("#Progress").hide();
}

function onSuccessGetVersion(retVal) {
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#version").html(retVal.Payload.toString());
    }
    else {
        alert(retVal.ErrorMessage);
    }
}

/* Gets called on a successful WCF service call. Renders the output to the user. */
function onSuccessGetTerms(retVal) {
    HideProgress();
    var inEventHandler = false;
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#vw_Parent").tmpl(retVal).appendTo("#tree");
        $("#tree").dynatree({
            persist: true,
            checkbox: true,
            selectMode: 2,
            onSelect: function (flag, dtnode) {
                // This will happen each time a check box is selected/deselected
                var selectedNodes = dtnode.tree.getSelectedNodes();
                var selectedKeys = $.map(selectedNodes, function (node) {
                    return node.data.key;
                });
                // Set the hidden input field's value to the selected items
                $('#SelectedItems').val(selectedKeys.join(","));

                // Select child nodes
                // Ignore, if this is a recursive call
                if (!inEventHandler) {
                    inEventHandler = true;
                    // Select all children of currently selected node
                    try {
                        inEventHandler = true;
                        dtnode.visit(function (childNode) {
                            childNode.select(flag);
                        });
                    }
                    finally {
                        inEventHandler = false;
                    }
                }
            },
            onClick: function (node) {
                if (!node.data.isFolder) {
                    ShowProgress();
                    CallWebService("/_vti_bin/Sukul.SharePoint.Taxomatic/TaxomaticService.svc/GetSingleTerm", node.data.key.toString(), onSuccessGetTerm); ;
                }
            },
            onKeydown: function (node, event) {
                // Eat keyboard events, when a menu is open        
                if ($(".contextMenu:visible").length > 0) return false; switch (event.which) {
                    // Open context menu on [Space] key (simulate right click)                    
                    case 32: // [Space]         
                        $(node.span).trigger("mousedown", { preventDefault: true, button: 2 })
              .trigger("mouseup", { preventDefault: true, pageX: node.span.offsetLeft, pageY: node.span.offsetTop, button: 2 }); return false;
                        // Handle Ctrl-C, -X and -V       
                    case 67: if (event.ctrlKey) {
                            // Ctrl-C 
                            copyPaste("copy", node); return false;
                        } break; case 86: if (event.ctrlKey) {
                            // Ctrl-V  
                            copyPaste("paste", node); return false;
                        } break; case 88: if (event.ctrlKey) {
                            // Ctrl-X            
                            copyPaste("cut", node); return false;
                        } break;
                }
            }
        });

        // Add context menu handler to tree nodes    
        bindContextMenu();

        //        onClick: function (node, event) {
        //                // Eat mouse events, while a menu is open        
        //                if ($(".contextMenu:visible").length > 0) { return false; }
        //            },
    }
    else {
        alert(retVal.ErrorMessage);        
    }
}

function onSuccessGetTerm(retVal) {
    HideProgress();
    var inEventHandler = false;
    retVal = JSON.parse(retVal);
    if (retVal.IsSuccess == true) {
        $("#divTerm").html("");
        $("#vw_Term").html("").tmpl(retVal.Payload).appendTo("#divTerm");
    }
    else {
        alert(retVal.ErrorMessage);
    }
}

/* Gets called on an unexpected error */
function onFail(err) {
    HideProgress();
    alert(err._message);
}

/* Displays the error message to the user */
function ErrorHandler(retVal) {
    // $("#errorDiv").show();
    // $("#resultsDiv").hide();
    // note: chaining does not work for templates
    // $("#errorDialogDetails").html("");
    // $("#errorDiv").html("");
    // $("#vw_Error").tmpl(retVal).appendTo("#errorDialogDetails");
    // $("#vw_Error").tmpl(retVal).appendTo("#errorDiv")
    // $("#errorDialog").dialog({ width: 600 });

    var clipboardNode = null;
    var pasteMode = null;
}

function bindContextMenu() {
    // Add context menu to all nodes:    alert("Adding context menu");
    //    $(".mymenu")
    //			.destroyContextMenu() // unbind first, to prevent duplicates
    //			.contextMenu({ menu: "myMenu" }, function (action, el, pos) {
    //			    // The event was bound to the <span> tag, but the node object
    //			    // is stored in the parent <li> tag
    //			    var node = el.parent().attr("dtnode");
    //			    switch (action) {
    //			        case "cut":
    //			        case "copy":
    //			        case "paste":
    //			            copyPaste(action, node);
    //			            break;
    //			        default:
    //			            alert("Todo: appply action '" + action + "' to node " + node);
    //			    }
    //			});
}
